//
//  WxlAPPTools.m
//  段子手
//
//  Created by dllo on 16/3/17.
//  Copyright © 2016年 JokesTeam. All rights reserved.
//

#import "WxlAPPTools.h"

@implementation WxlAPPTools

+ (void)GETWithURL:(NSString *)urlStr
               par:(NSDictionary *)dic
           success:(void (^)(id))responseObj filed:(void (^)(NSError *))err
{
    
    //    // 1. 获取AFN网络请求的Manager
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFNetworkReachabilityManager *netWorkManger = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要监测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    // 获取沙盒路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    // 文件管理器
    NSFileManager *manger = [NSFileManager defaultManager];
    // 使用文件管理器创建一个文件夹
    // 拼文件夹路径
    NSString *totoroCaches = [documentPath stringByAppendingPathComponent:@"totoroCaches"];
    
    BOOL resultFile = [manger createDirectoryAtPath:totoroCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (resultFile) {
//        NSLog(@"创建缓存的文件夹成功");
    } else {
//        NSLog(@"创建存缓存的文件夹失败");
    }
    // 拼接缓存路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist", [urlStr hash]];
    // 将这个缓存写在自己创建的文件夹下面
    NSString *textFilPath = [totoroCaches
                             stringByAppendingPathComponent:path];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
    }];
    
    NSString *str = [NSString stringWithFormat:@"%@",urlStr];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 有的返回的数据格式，AFN不支持解析，所以我们要设置一下。让AFN支持。
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [manager GET:str parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [netWorkManger stopMonitoring];
        responseObj(responseObject);
        
        BOOL result = [responseObject writeToFile:textFilPath atomically:YES];
        
        if (result) {
//                        NSLog(@"写入成功");
        }else{
            
//                        NSLog(@"写入失败");
        }
        //        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
        //        NSLog(@"%@",dic);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        err(error);
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
        responseObj(dic);
    }];
}



+ (void)POSTWithURL:(NSString *)urlStr
                par:(NSDictionary *)dic
            success:(void (^)(id))response filed:(void (^)(NSError *))err
{
    
    // 1. 获取AFN网络请求的Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    // 1. 获取AFN网络请求的Manager
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    AFNetworkReachabilityManager *netWorkManger = [AFNetworkReachabilityManager sharedManager];
    
    // 如果要监测网络状态的变化,必须用检测管理器的单例的startMonitoring
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    // 获取沙盒路径
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    // 文件管理器
    NSFileManager *manger = [NSFileManager defaultManager];
    // 使用文件管理器创建一个文件夹
    // 拼文件夹路径
    NSString *totoroCaches = [documentPath stringByAppendingPathComponent:@"totoroCaches"];
    
    BOOL resultFile = [manger createDirectoryAtPath:totoroCaches withIntermediateDirectories:YES attributes:nil error:nil];
    if (resultFile) {
//        NSLog(@"创建缓存的文件夹成功");
    } else {
//        NSLog(@"创建存缓存的文件夹失败");
    }
    // 拼接缓存路径
    NSString *path = [NSString stringWithFormat:@"%ld.plist",[urlStr hash]];
    // 将这个缓存写在自己创建的文件夹下面
    NSString *textFilPath = [totoroCaches
                             stringByAppendingPathComponent:path];
    
    // 检测网络连接的单例,网络变化时的回调方法
    [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        //        NSLog(@"网络状态 = %ld",status);
    }];
    
    NSString *str = [NSString stringWithFormat:@"%@",urlStr];
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", @"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", @"text/plain", @"application/x-javascript", @"application/javascript",nil]];
    
    str = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    [manager POST:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [netWorkManger stopMonitoring];
        response(responseObject);
        
        BOOL result = [responseObject writeToFile:textFilPath atomically:YES];
        
        if (result) {
//            NSLog(@"写入成功");
        }else{
            
//            NSLog(@"写入失败");
        }
        //        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
        //        NSLog(@"%@",dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        err(error);
        
        id result = [NSMutableDictionary dictionaryWithContentsOfFile:textFilPath];
        response(result);
        
    }];
    
    
}

/** 计算文本宽度 文字自适应的方法 */
+ (CGRect)scripeSuitWidthWithString:(NSString *)string Font:(CGFloat)font Size:(CGSize)size {
    
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:font], NSFontAttributeName, nil];
    
    // 通过文字大小获取文本rect
    CGRect rect = [string boundingRectWithSize:CGSizeMake(size.width, size.height) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:dic context:nil];
    
    // 返回 文本宽度
    return rect;
}

/** 十六进制颜色转换 */
+ (UIColor *) hexStringToColor: (NSString *) stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 charactersif ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appearsif ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}


//将数据保存到本地
+ (void)saveDataToLocal:(id)data keys:(NSString *)key {
    NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
    
    [preferences setObject:data forKey:key];
    
}

//本地是否有相关数据
+ (BOOL)localHaveDataWithKey:(NSString *)key {
    NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
    NSData* data = [preferences objectForKey:key];
    if (data) {
        return YES;
    }
    return NO;
}

//从本地获取数据
+ (id)takeDataFromLocalWithKey:(NSString *)key {
    
    NSUserDefaults* preferences = [NSUserDefaults standardUserDefaults];
    
    NSData* data = [preferences objectForKey:key];
    
    if (data) {
        
       return data;
    }
    else {
        NSLog(@"未从本地获得图片");
    }
    return nil;
}


@end
